import { ApiBase } from "./index.js";

function chooseImage () {
	return new Promise(resolve => {
		uni.chooseImage({
			sourceType: ["album", "camera"],
			success(ev) {
				resolve({success : true, data : ev.tempFilePaths});
			},
			fail(e) {
				resolve({success : false, data : null});
			}
		})
	});
}

function single_upload_action (filePath){
	return new Promise(resolve => {
		const url = ApiBase + "/app-api/att/single-upload";

		uni.uploadFile({
			url,
			filePath,
			name : "file",
			success(ev) {
				if(ev.statusCode === 200){
					const res = JSON.parse(ev.data);
					if(res.success){
						resolve({success : true, data : res.data, message : ""});
					} else {
						resolve({success : false, data : null, message : "上传失败"});
					}
				} else {
					resolve({success : false, data : null, message : "上传失败"});
				}
			},
			fail(ev) {
				resolve({success : false, data : null, message : "未知错误"});
			}
		});
	});
}

async function single_upload(files){
	const uresult = [];
	for (let i=0; i<files.length; i++) {
		const result = await single_upload_action(files[i]);
		uresult.push({
			success : result.success,
			data : result.data,
			filePath : files[i]
		});
	}
	return {success : true, data : uresult, message : ""};
}

async function mulity_upload (files){
	return new Promise(resolve => {
		const url = ApiBase + "/app-api/att/multiple-upload";
		const file_list = files.map((d, i) => {
			return {
				name: "file_" + i,
				uri: d
			}
		});
		uni.uploadFile({
			url,
			files : file_list,
			success(ev) {
				if(ev.statusCode === 200){
					const res = JSON.parse(ev.data);
					if(res.success){
						resolve({success : true, data : res.data, message : ""});
					} else {
						resolve({success : false, data : null, message : "上传失败"});
					}
				} else {
					resolve({success : false, data : null, message : "上传失败"});
				}
			},
			fail(ev) {
				resolve({success : false, data : null, message : "未知错误"});
			}
		});
	});
}

export async function mupload () {
	const ires = await chooseImage();
	if(!ires.success) return ires;
	
	uni.showLoading({
		title: "图片上传中..."
	});
	const result = await mulity_upload(ires.data);
	uni.hideLoading();
	return result;
}

